package pt.utl.ist.project_ccu;
import java.util.ArrayList;
import java.util.HashMap;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.RelativeLayout;
import android.widget.Toast;

public class MobileGallery extends Activity {

	//Array que associa o valor de cada checkbox
	//Cada foto tem uma checkbox
	private boolean[] thumbnailsselection;
	private ArrayList<ViewHolder> _viewHolders;

	private int nrSelectedImages = 0;

	HashMap<String,Button> buttons;
	Button selectBtn;
	
	ImageAdapter imgad;

	//Fotos a serem apresentadas na galeria
	private Integer[] mImageIds = {
			R.drawable.bebe3,
			R.drawable.image1,
			R.drawable.image2,
			R.drawable.image3,
			R.drawable.foto1,
			R.drawable.foto2,
			R.drawable.foto4,
			R.drawable.foto3,
			R.drawable.bebe1,
			R.drawable.bebe2,
			R.drawable.bebe4,
			R.drawable.bebe5,
			R.drawable.bebe6,
			R.drawable.bebe7,
			R.drawable.bebe8, 
			R.drawable.image1,
			R.drawable.image1,
			R.drawable.image3,
			R.drawable.image1,
			R.drawable.image1,
			R.drawable.image3,
			R.drawable.image1,
			R.drawable.image1,
			R.drawable.image3,
	};

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.grid_layout);
		_viewHolders = new ArrayList<ViewHolder>();
		GridView gridView = (GridView) findViewById(R.id.grid_view);
		
		Display display = this.getWindowManager().getDefaultDisplay();
		int _screenWidth,_screenHeight;
		_screenWidth = display.getWidth();
		_screenHeight = display.getHeight();
		imgad = new ImageAdapter(this,_screenHeight);
		gridView.setAdapter(imgad);
		
		RelativeLayout top = (RelativeLayout) findViewById(R.id.relativeLayoutTop);
		LayoutParams params = top.getLayoutParams();
		params.height = (int) (_screenHeight*0.85);
		top.setLayoutParams(params);
		
		RelativeLayout bottom = (RelativeLayout) findViewById(R.id.relativeLayoutBottom);
		RelativeLayout.LayoutParams params2 = (RelativeLayout.LayoutParams)bottom.getLayoutParams();
		params2.topMargin = (int) (_screenHeight*0.85);
		bottom.setLayoutParams(params2);
		
		GridView gridImages = (GridView) findViewById(R.id.grid_view);
		int nr_of_images_width = _screenWidth/3;
		Log.i("TAMANHO_COMPRIMENTO",_screenWidth+"");
		Log.i("NR_IMAGES",nr_of_images_width+"");
		gridImages.setColumnWidth(nr_of_images_width);

		//Array do tamanho do numero de fotos a apresentar
		this.thumbnailsselection = new boolean[mImageIds.length];

		final Button selectBtn = (Button) findViewById(R.id.selectBtn);
		selectBtn.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				final int len = thumbnailsselection.length;
				ArrayList<Integer> selectImages = new ArrayList<Integer>();

				if(nrSelectedImages != 0) {
					for (int i =0; i<len; i++)
					{
						if (thumbnailsselection[i]){
							selectImages.add(mImageIds[i]);
						}
					}

					Intent intent = new Intent(getApplicationContext(), AddTags.class);
					intent.putExtra("idImages", selectImages);
					startActivity(intent);
				}

				else {
					Toast.makeText(getApplicationContext(),
							"Please select at least one image",
							Toast.LENGTH_LONG).show();
				}
			}
		});
		
		Button selectAll = (Button) findViewById(R.id.selectAll);
		selectAll.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				
				GridView gridView = (GridView) findViewById(R.id.grid_view);
				
				for(int i = 0;i < thumbnailsselection.length;i++) {
					thumbnailsselection[i] = true;
					nrSelectedImages = thumbnailsselection.length;
				}
				
				for(int i = 0; i < gridView.getChildCount(); i++){
					((CheckBox)((RelativeLayout)gridView.getChildAt(i)).getChildAt(1)).setChecked(true);
				}
			}

		});
		
		Button selectNone = (Button) findViewById(R.id.selectNothing);
		selectNone.setOnClickListener(new OnClickListener() {

			public void onClick(View arg0) {
				
				GridView gridView = (GridView) findViewById(R.id.grid_view);
				
				for(int i = 0;i < thumbnailsselection.length;i++){
					thumbnailsselection[i] = false;
					nrSelectedImages = 0;
				}
				
				for(int i = 0; i < gridView.getChildCount(); i++){
					((CheckBox)((RelativeLayout)gridView.getChildAt(i)).getChildAt(1)).setChecked(false);
				}
			}
		});
	}

	public class ImageAdapter extends BaseAdapter {
		int mGalleryItemBackground;
		private Context mContext;
		private LayoutInflater mInflater;
		private int _screenHeight;
		ViewHolder holder;

		public ImageAdapter(Context c, int screenHeight) {
			mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			mContext = c;
			_screenHeight = screenHeight;
		}
		
		public int getCount() {
			return mImageIds.length;
		}

		public Object getItem(int position) {
			return position;
		}

		public long getItemId(int position) {
			return position;
		}
		
		public View getView(int position, View convertView, ViewGroup parent) {
			
			if(convertView == null) {
				holder = new ViewHolder();
				convertView = mInflater.inflate(R.layout.galleryitem, null);
				holder.imageview = (ImageView) convertView.findViewById(R.id.thumbImage);
				holder.checkbox = (CheckBox) convertView.findViewById(R.id.itemCheckBox);
				convertView.setTag(holder);		
			}
			else {
				holder = (ViewHolder) convertView.getTag();
			}
			
			holder.checkbox.setId(position);
			holder.imageview.setId(position);

			holder.checkbox.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {

					// TODO Auto-generated method stub
					CheckBox cb = (CheckBox) v;
					int id = cb.getId();
					if (thumbnailsselection[id]){
						nrSelectedImages--;
						cb.setChecked(false);
						thumbnailsselection[id] = false;
					} else {
						nrSelectedImages++;
						cb.setChecked(true);
						thumbnailsselection[id] = true;
					}
				}

			});

			holder.imageview.setImageBitmap(
					decodeSampledBitmapFromResource(getResources(), mImageIds[position], 500, 500));

			holder.imageview.setLayoutParams(new RelativeLayout.LayoutParams(500, (int) (_screenHeight*0.21)));
			holder.imageview.setScaleType(ImageView.ScaleType.FIT_XY);
			holder.checkbox.setChecked(thumbnailsselection[position]);
			holder.id = position;

			final int pos = position;

			holder.imageview.setOnLongClickListener(new OnLongClickListener() {

				@SuppressLint("NewApi")
				public boolean onLongClick(View arg0) {
					/*
					MediaMetadataRetriever metaRetriever = new MediaMetadataRetriever();
					metaRetriever.setDataSource(getResources().getResourceEntryName(mImageIds[pos]));
					 */
					Intent intent = new Intent(getApplicationContext(),Photo_META.class);
					intent.putExtra("idName", mImageIds[pos]+"");
					startActivity(intent);
					return true;
				}

			});

			return convertView;
		}

		public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
			int width = bm.getWidth();
			int height = bm.getHeight();
			float scaleWidth = ((float) newWidth) / width;
			float scaleHeight = ((float) newHeight) / height;
			// CREATE A MATRIX FOR THE MANIPULATION
			Matrix matrix = new Matrix();
			// RESIZE THE BIT MAP
			matrix.postScale(scaleWidth, scaleHeight);

			// "RECREATE" THE NEW BITMAP
			Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
			return resizedBitmap;
		}

		public int getScale(int originalWidth,int originalHeight,
				final int requiredWidth,final int requiredHeight)
		{
			//a scale of 1 means the original dimensions 
			//of the image are maintained
			int scale=1;

			//calculate scale only if the height or width of 
			//the image exceeds the required value.
			if((originalWidth>requiredWidth) || (originalHeight>requiredHeight)) 
			{
				//calculate scale with respect to
				//the smaller dimension
				if(originalWidth<originalHeight)
					scale=Math.round((float)originalWidth/requiredWidth);
				else
					scale=Math.round((float)originalHeight/requiredHeight);

			}

			return scale;
		}

		public int calculateInSampleSize(
				BitmapFactory.Options options, int reqWidth, int reqHeight) {
			// Raw height and width of image
			final int height = options.outHeight;
			final int width = options.outWidth;
			int inSampleSize = 1;

			if (height > reqHeight || width > reqWidth) {
				if (width > height) {
					inSampleSize = Math.round((float)height / (float)reqHeight);
				} else {
					inSampleSize = Math.round((float)width / (float)reqWidth);
				}
			}
			return inSampleSize;
		}
		public Bitmap decodeSampledBitmapFromResource(Resources res, int resId,
				int reqWidth, int reqHeight) {

			// First decode with inJustDecodeBounds=true to check dimensions
			final BitmapFactory.Options options = new BitmapFactory.Options();
			options.inJustDecodeBounds = true;
			BitmapFactory.decodeResource(res, resId, options);

			// Calculate inSampleSize
			options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);

			// Decode bitmap with inSampleSize set
			options.inJustDecodeBounds = false;
			return BitmapFactory.decodeResource(res, resId, options);
		}
	}

	class ViewHolder {
		ImageView imageview;
		CheckBox checkbox;
		int id;
	}
}